import { OperationlogsResponse, TypeResponse } from 'admin/schema/OperationLog';
import {
  createOperationLogsDownloadTask,
  getOperationLogsList,
  getOperationTypeList,
} from 'admin/servers/servers';
import { Button, DatePicker, Form, FormInstance, Input, message, Select, Space, Table } from 'antd';
import moment from 'moment';
import React, { Component } from 'react';
import { clearNull, getTableIndex } from 'utils/tools';
import './style.scss';

const { RangePicker } = DatePicker;
const { Option } = Select;
interface Props {}
interface State {}

/**
 * 操作日志
 */
export default class OperationLog extends Component<Props, State> {
  formRef = React.createRef<FormInstance>();
  state = {
    searchForm: {},
    pageInfo: {
      pageTotal: 0,
      pageNum: 1,
      pageSize: 10,
    },
    tableData: [],
    tableColumns: [
      {
        title: '序号',
        key: 'index',
        dataIndex: 'index',
        fixed: 'left',
        width: 70,
        render: (text: any, record: OperationlogsResponse[0], index: number) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      },
      {
        title: '账号',
        key: 'userName',
        dataIndex: 'userName',
        width: 200,
      },
      {
        title: '用户名',
        key: 'nickName',
        dataIndex: 'nickName',
        width: 200,
      },
      {
        title: '操作时间',
        key: 'operationTime',
        dataIndex: 'operationTime',
        width: 200,
      },
      {
        title: 'IP地址',
        key: 'userIp',
        dataIndex: 'userIp',
        width: 200,
      },
      {
        title: '操作类型',
        key: 'operationTypeName',
        dataIndex: 'operationTypeName',
        width: 200,
      },
      {
        title: '操作内容',
        key: 'operationContent',
        dataIndex: 'operationContent',
      },
    ],
    tableLoading: false,
    operationList: [] as TypeResponse,
  };
  componentDidMount() {
    this.fetchList();
    this.fetchOperationList();
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }

  /**
   * 查询table数据
   */
  private async fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { searchForm, pageInfo } = this.state;
    try {
      const res = await getOperationLogsList(
        clearNull({
          ...searchForm,
          pageNo: pageInfo.pageNum,
          pageSize: pageInfo.pageSize,
        })
      );
      pageInfo.pageTotal = res.count as number;
      this.setState({
        tableData: res.data,
        pageInfo: pageInfo,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      tableLoading: false,
    });
  }

  /**
   * 表格行操作后，重置列表
   */
  handleSearch = (values: any) => {
    const { conditions, nickName, rangeTime, operationType } = values;
    const beginTime = rangeTime ? rangeTime[0].format('YYYY-MM-DD') : undefined;
    const endTime = rangeTime ? rangeTime[1]?.format('YYYY-MM-DD') : undefined;
    this.setState({
      searchForm: { conditions, nickName, beginTime, endTime, operationType },
    });
    this.jumpPage(1);
  };

  /**
   * 重置搜索列表
   */
  handleReset = () => {
    this.formRef.current?.resetFields();
    this.setState(
      {
        searchForm: {},
      },
      () => {
        this.jumpPage(1);
      }
    );
  };

  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }

  /** 创建下载任务 */
  private handleExport(): void {
    const { searchForm } = this.state;
    const postData = clearNull({
      ...searchForm,
    });
    createOperationLogsDownloadTask(postData as any).then(res => {
      if (res.code === 0) {
        // 创建下载任务
        message.warning('数据正在准备中，请稍候到下载管理中下载');
      } else {
        message.error(`${res.tips}(错误码:${res.code})`);
      }
    });
  }

  /**获取操作类型*/
  private async fetchOperationList(): Promise<void> {
    try {
      const res = await getOperationTypeList();
      this.setState({
        operationList: res.data,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }

  render() {
    const {
      state: {
        tableColumns,
        tableData,
        pageInfo: { pageNum, pageSize, pageTotal },
        tableLoading,
        operationList,
      },
    } = this;

    const disabledDate = (current: any) => {
      // 不可选择：3个月前
      return current && current < moment().subtract(3, 'months');
    };
    return (
      <>
        <div className="mgr-header operation-log-header">
          <div className="mgr-header-left">
            <Form ref={this.formRef} layout="inline" onFinish={this.handleSearch}>
              <Form.Item
                label=""
                name="conditions"
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input
                  allowClear
                  className="sound-header-name"
                  placeholder="请输入账号/IP地址"
                  style={{ width: 300 }}
                />
              </Form.Item>
              <Form.Item
                label="用户名"
                name="nickName"
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input
                  allowClear
                  className="sound-header-name"
                  placeholder="请输入"
                  style={{ width: 200 }}
                />
              </Form.Item>
              <Form.Item label="操作日期" name="rangeTime">
                <RangePicker
                  showTime
                  format="YYYY-MM-DD"
                  disabledDate={disabledDate}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                  }}
                  allowClear
                />
              </Form.Item>
              <Form.Item label="操作类型" name="operationType">
                <Select
                  style={{ width: 230 }}
                  allowClear
                  mode="multiple"
                  autoClearSearchValue={false}
                  showSearch
                  placeholder="请选择操作类型"
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                  optionFilterProp="children"
                  maxTagCount={2}
                  filterOption={(input, option) =>
                    (option as any).children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {operationList.map(item => {
                    return (
                      <Option key={item.typeId} value={item.typeId}>
                        {item.typeName}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
              <Space size="middle">
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button type="primary" ghost onClick={this.handleReset}>
                  重置
                </Button>
              </Space>
            </Form>
          </div>
          <div className="mgr-header-right">
            <Button
              type="primary"
              onClick={() => {
                this.handleExport();
              }}
            >
              导出
            </Button>
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            dataSource={tableData}
            scroll={{ x: 'max-content' }}
            columns={tableColumns as any}
            rowKey={(record: OperationlogsResponse[0], index) => `table${record.userName}${index}`}
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
      </>
    );
  }
}
